package com.turman.coroutionsample.paging

import androidx.paging.PagingSource
import androidx.paging.PagingState
import com.turman.coroutionsample.net.InfoItem
import com.turman.coroutionsample.net.RetrofitClient

class GithubPagingSource : PagingSource<Int, InfoItem>() {
    private var currentLoadTotal = 0

    override fun getRefreshKey(state: PagingState<Int, InfoItem>): Int? {
        return state.anchorPosition?.let {
            val anchorPage = state.closestPageToPosition(it)
            anchorPage?.prevKey?.plus(1) ?: anchorPage?.nextKey?.minus(1)
        }
    }

    override suspend fun load(params: LoadParams<Int>): LoadResult<Int, InfoItem> {
        val currentPage = params.key ?: 0 //如果key为空则为第一页
        val pageSize = params.loadSize  //页宽继承上一次加载数据的页宽
        val searchKey = "kotlin"

        try {
            val result = RetrofitClient.githubservice.searchRepositors(
                words = searchKey,
                page = currentPage,
                pageSize = pageSize
            )
            currentLoadTotal += result.items.size //当前加载了多少条

//        val prevKey = if (currentPage == 0) null else currentPage - 1 //如果是意义页为空
//        val nextKey =
//            if (result.total_count <= currentLoadTotal) null else currentPage + 1 //判断还有没有下一页数据

            var prevKey: Int? = null
            var nextKey: Int? = null

            if (currentPage == 0) {
                prevKey = null
                nextKey = 3 //这里pager config中设置initloadsize为30 所以。。。。。
            } else {
                prevKey = currentPage - 1
                nextKey = if (result.total_count <= currentLoadTotal) null else currentPage + 1
            }

            return LoadResult.Page(
                data = result.items,
                prevKey = prevKey,
                nextKey = nextKey
            )
        } catch (e:Exception) {
            e.printStackTrace()
            return LoadResult.Page(
                data = listOf(),
                prevKey = null,
                nextKey = null
            )
        }

    }
}